package com.likk.usermanage.controller;

import com.likk.usermanage.ftp.FtpProperty;
import com.likk.usermanage.utils.FtpUtil;
import com.likk.usermanage.utils.UploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author: likai
 * @CreateTime: 2019-04-08 20:58
 */
@Controller
@RequestMapping("ftp")
public class UploadController {

    @Autowired
    private FtpProperty ftpProperty;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @RequestMapping(value = "imgUpload", method = RequestMethod.POST)
    public ResponseEntity<String> upload(@RequestParam("file")MultipartFile file){
        try {
            // 获取要保存的目录
            String directory = UploadUtils.getPath(2);
            String savePath = ftpProperty.getBasePath() + directory ;

            // 将文件上传至ftp服务器
            FtpUtil.uploadFile(ftpProperty.getHost(), ftpProperty.getUsername(), ftpProperty.getPassword(), ftpProperty.getPort(),
                    savePath, file.getOriginalFilename(), file.getInputStream());

            // 图片展示路径
            String imageURL = ftpProperty.getImagesBaseURL()+ directory + "/" + file.getOriginalFilename();

            return new ResponseEntity<String>(imageURL, HttpStatus.OK);
        } catch (Exception e){
            e.printStackTrace();

            return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
